/**
 * Created by 刘柘林 on 2016/12/12.
 */

var express = require('express');
var url = require('url');
var querystring = require('querystring');
var router = express.Router();
var Admin = require('../models').Admin;
var User = require('../models').User;
var pwdHash = require('password-hash');
var utils = require('../utils');

router.get('/', function (req, res, next) {
    res.render('admin/admin_infor', {
            title: '管理员',
            admin: req.session.admin
    });
});

/*
 Admin Login
 */
router.get('/login',function (req, res, next) {
    res.render('admin/admin_login',{title: '登录'});
}).post('/login', function (req, res, next) {
    var form = {
        name: req.body.name,
        password: req.body.password
    };
    Admin.findByName(form.name).then(function (admin) {
        if(!admin){
            res.send("Admin not exits!");
            //res.redirect('/');
        }
        if(!pwdHash.verify(form.password, admin.password)){
            res.send("Password not correct!");
            //res.redirect('/login');
        }else {
            utils.adminLoginSession(req, res, admin);
            res.redirect('/admin');
        }
    })
});


/*
 * log out*/
router.get('/logout', function (req, res, next) {
    utils.adminLogoutSession(req);
    return res.redirect('/admin');
});

/*show user*/
router.get('/show_users', function (req, res, next) {
    User.findAll().then(function (users) {
        res.render('admin/show_users',{
            title: '展示数据',
            Users: users,
            admin: req.session.admin
        });
    });
}).post('/show_users', function (req, res, next) {
    var user_email = req.body.user_email;
    if (user_email != undefined) {
        User.deleteByEmail(user_email);
    }
});

module.exports = router;